<template>
  <view class="page-container">
    <!-- 固定头部导航 -->
    <view class="fixed-header" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-bar">
        <view class="left" @tap="goBack">
          <text class="back-icon">〈</text>
        </view>
        <view class="title-container">
          <view class="avatar-title">
            <image class="avatar" :src="deviceInfo?.avatar || deviceInfo?.icon || defaultAvatar" mode="aspectFill" />
            <view class="title-info">
              <text class="name">{{ deviceInfo?.name }}</text>
              <text class="creator">@{{ deviceInfo?.creatorName }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 可滚动的消息列表 -->
    <scroll-view 
      class="message-list" 
      scroll-y 
      :scroll-into-view="lastMessageId" 
      :scroll-with-animation="true"
      :style="{ top: `calc(${statusBarHeight}px + 88rpx)` }"
      @scrolltoupper="loadMoreHistory"
    >
      <block v-if="messages.length">
        <template v-for="(msg, index) in messages" :key="msg.id">
          <!-- 居中的时间戳 -->
          <view v-if="shouldShowTimestamp(msg, messages[index - 1])" class="time-stamp-wrapper">
            <view class="time-stamp">{{ formatTime(msg.timestamp) }}</view>
          </view>

          <!-- 消息气泡 -->
          <view :id="`msg-${msg.id}`" :class="['message-item', msg.role]">
            <image class="avatar" :src="msg.role === 'assistant' ? deviceInfo?.avatar || deviceInfo?.icon || defaultAvatar : userInfo?.avatar || defaultAvatar"
              mode="aspectFill" />
            <view class="content">{{ msg.content }}</view>
          </view>
        </template>
      </block>
    </scroll-view>

    <!-- 固定底部输入区 -->
    <view class="fixed-footer">
      <view class="input-box">
        <input v-model="inputContent" class="input" type="text" placeholder="发送消息..." confirm-type="send"
          @confirm="sendMessage" />
        <button class="send-btn" :class="{ active: inputContent }" @tap="sendMessage">
          发送
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, nextTick, watch, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores/modules/user'
import { useChatStore } from '@/stores/modules/chat'
import { useDeviceStore } from '@/stores/modules/device'
import { system } from '@/utils'
import api from '@/api/modules' // 导入API模块

const statusBarHeight = system.getStatusBarHeight()
const userStore = useUserStore()
const chatStore = useChatStore()
const deviceStore = useDeviceStore()

// 默认头像
const defaultAvatar = '/static/images/default-avatar.png'

// 状态管理
const userInfo = computed(() => userStore.userInfo)
const messages = computed(() => chatStore.messages)
const inputContent = ref('')
const deviceInfo = ref(null)
const lastMessageId = ref('')

// 监听消息变化
watch(messages, (newMessages) => {
  console.log('Messages updated:', newMessages)
  nextTick(() => {
    scrollToBottom()
  })
}, {
  deep: true
})

// 发送消息
const sendMessage = async () => {
  const content = inputContent.value?.trim()
  if (!content || chatStore.loading) return

  try {
    // 清空输入框
    inputContent.value = ''
    
    // 构建用户消息对象
    const userMessage = {
      id: Date.now(),
      role: 'user',
      content: content,
      timestamp: Date.now()
    }
    
    // 添加用户消息到列表
    chatStore.addMessage(userMessage)
    
    // 创建 AI 响应消息对象
    const assistantMessage = {
      id: Date.now() + 1,
      role: 'assistant',
      content: '',
      timestamp: Date.now()
    }
    
    // 添加到消息列表
    chatStore.addMessage(assistantMessage)
    
    // 构建请求数据
    const requestData = {
      content: content,
      deviceId: deviceInfo.value?.id,
      stream: false
    }
    
    try {
      // 发送普通请求
      const res = await api.chat.sendMessage(requestData)
      
      if (res.data && res.data.content) {
        // 获取完整响应内容
        const fullContent = res.data.content
        
        // 模拟流式输出
        let currentIndex = 0
        const totalLength = fullContent.length
        
        // 定义打字效果函数
        const typeEffect = () => {
          if (currentIndex < totalLength) {
            // 每次添加1-3个字符，模拟不同打字速度
            const chunkSize = Math.floor(Math.random() * 3) + 1
            const nextIndex = Math.min(currentIndex + chunkSize, totalLength)
            
            // 添加新内容
            const newChunk = fullContent.substring(currentIndex, nextIndex)
            assistantMessage.content += newChunk
            
            // 更新索引
            currentIndex = nextIndex
            
            // 强制更新消息列表
            chatStore.messages = [...chatStore.messages]
            
            // 继续打字效果，速度随机在50-150ms之间
            const delay = Math.floor(Math.random() * 100) + 50
            setTimeout(typeEffect, delay)
          }
        }
        
        // 开始打字效果
        typeEffect()
      }
    } catch (error) {
      console.error('请求失败:', error)
      throw error
    }
  } catch (error) {
    console.error('发送失败:', error)
    uni.showToast({
      title: '发送失败',
      icon: 'none'
    })
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messages.value?.length) {
    lastMessageId.value = `msg-${messages.value[messages.value.length - 1].id}`
    console.log('Scrolling to message:', lastMessageId.value)
  }
}

// 初始化聊天
onLoad((options) => {
  console.log('Chat page loaded with options:', options)
  initChat(parseInt(options.id))
})

// chat.vue 中的 initChat 方法
const initChat = async (deviceId) => {
  // 确保deviceId是有效的数字
  const numericDeviceId = parseInt(deviceId);
  if (isNaN(numericDeviceId) || numericDeviceId <= 0) {
    console.error('无效的设备ID:', deviceId);
    uni.showToast({
      title: '无效的设备ID',
      icon: 'none'
    });
    return;
  }

  try {
    console.log('Initializing chat with device ID:', numericDeviceId);
    chatStore.setCurrentDeviceId(numericDeviceId);

    // 先加载设备信息
    await deviceStore.loadPrivateDevices();
    await deviceStore.loadPublicDevices({ current: 1, size: 10 });
    await deviceStore.loadCollectedDevices();
    
    // 从所有设备列表中查找设备
    let device = deviceStore.privateDevices.find(d => d.id === numericDeviceId);
    if (!device) {
      device = deviceStore.publicDevices.find(d => d.id === numericDeviceId);
    }
    if (!device) {
      device = deviceStore.collectedDevices.find(d => d.id === numericDeviceId);
    }

    if (!device) {
      throw new Error('设备不存在');
    }
    
    deviceInfo.value = device;
    
    // 获取历史消息
    try {
      console.log('准备获取历史消息，设备ID:', numericDeviceId);
      
      // 使用store的getMessages方法
      const messages = await chatStore.getMessages(numericDeviceId, 1, 20);
      
      // 如果没有消息，添加自我介绍
      if (!messages || messages.length === 0) {
        const introMessage = {
          id: Date.now(),
          role: 'assistant',
          content: device.description,
          timestamp: Date.now()
        };
        chatStore.addMessage(introMessage);
      }
    } catch (error) {
      console.error('获取历史消息失败:', error);
      // 添加自我介绍消息
      const introMessage = {
        id: Date.now(),
        role: 'assistant',
        content: device.description,
        timestamp: Date.now()
      };
      chatStore.addMessage(introMessage);
    }

  } catch (error) {
    console.error('初始化失败:', error);
    uni.showToast({
      title: '初始化失败',
      icon: 'none'
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 加载更多历史记录方法
const loadMoreHistory = async () => {
  if (chatStore.loading || !deviceInfo.value) return;

  try {
    const page = Math.floor(messages.value.length / 20) + 1;
    const deviceId = deviceInfo.value.id;
    
    if (!deviceId || isNaN(deviceId)) {
      console.error('无效的设备ID:', deviceId);
      return;
    }
    
    console.log('加载更多历史消息, 页码:', page, '设备ID:', deviceId);
    await chatStore.getMessages(deviceId, page, 20);
  } catch (error) {
    console.error('加载更多消息失败:', error);
  }
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 是否显示时间戳
const shouldShowTimestamp = (currentMsg, prevMsg) => {
  if (!currentMsg?.timestamp) return false
  if (!prevMsg?.timestamp) return true // 显示第一条消息的时间戳
  
  // 2分钟间隔显示时间戳
  return currentMsg.timestamp - prevMsg.timestamp > 2 * 60 * 1000
}

</script>

<style lang="scss">
.page-container {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  background: #f7f7f7;
  
  // 固定头部
  .fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: #fff;
    
    .nav-bar {
      height: 88rpx;
      display: flex;
      align-items: center;
      padding: 0 30rpx;
      background: #fff;
      border-bottom: 1px solid #eee;

      .left {
        margin-right: 20rpx;

        .back-icon {
          font-size: 36rpx;
          color: #333;
        }
      }

      .title-container {
        flex: 1;

        .avatar-title {
          display: flex;
          align-items: center;

          .avatar {
            width: 72rpx;
            height: 72rpx;
            border-radius: 50%;
            margin-right: 16rpx;
            background: #f5f6f7;
          }

          .title-info {
            display: flex;
            flex-direction: column;
            justify-content: center;

            .name {
              font-size: 32rpx;
              font-weight: 500;
              color: #333;
              line-height: 1.2;
            }

            .creator {
              font-size: 24rpx;
              color: #999;
              line-height: 1.2;
            }
          }
        }
      }
    }
  }

  // 消息列表区域
  .message-list {
    position: fixed;
    left: 0;
    right: 0;
    bottom: calc(112rpx + env(safe-area-inset-bottom));
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    background: #f7f7f7;
    padding: 20rpx 30rpx;

    // 时间戳
    .time-stamp-wrapper {
      display: flex;
      justify-content: center;
      padding: 16rpx 0;
      
      .time-stamp {
        padding: 8rpx 24rpx;
        font-size: 24rpx;
        color: #fff;
        background: rgba(0, 0, 0, 0.15);
        border-radius: 24rpx;
        text-align: center;
      }
    }

    // 消息项
    .message-item {
      display: flex;
      margin-bottom: 30rpx;

      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        flex-shrink: 0;
        background: #f5f6f7;
      }

      .content {
        max-width: 60%;
        padding: 20rpx 24rpx;
        border-radius: 12rpx;
        font-size: 28rpx;
        margin: 0 20rpx;
        word-break: break-all;
        line-height: 1.5;
      }

      // 用户消息
      &.user {
        flex-direction: row-reverse;

        .content {
          margin-right: 24rpx;
          background: #5677fc;
          color: #fff;
          border-radius: 16rpx 2rpx 16rpx 16rpx;
        }

        .avatar {
          margin-right: 50rpx;
        }
      }

      // AI助手消息
      &.assistant {
        .content {
          margin-left: 24rpx;
          background: #fff;
          color: #333;
          border-radius: 2rpx 16rpx 16rpx 16rpx;
        }

        .avatar {
          margin-left: 0rpx;
        }
      }
    }
  }

  // 底部输入区
  .fixed-footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    
    .input-box {
      padding: 20rpx;
      background: #f7f7f7;
      display: flex;
      align-items: center;
      border-top: 1px solid #eee;
      padding-bottom: calc(20rpx + env(safe-area-inset-bottom));

      .input {
        flex: 1;
        height: 72rpx;
        background: #fff;
        border-radius: 36rpx;
        padding: 0 30rpx;
        font-size: 28rpx;
      }

      .send-btn {
        width: 120rpx;
        height: 72rpx;
        line-height: 72rpx;
        text-align: center;
        margin-left: 20rpx;
        border-radius: 36rpx;
        font-size: 28rpx;
        background: #f0f0f0;
        color: #999;
        padding: 0;
        border: none;

        &.active {
          background: #5677fc;
          color: #fff;
        }

        &::after {
          border: none;
        }
      }
    }
  }
}
</style>